package com.lichao.argorithm.impl.array;

import com.lichao.argorithm.api.Stack;

public class ResizingArrayStack<T> implements Stack<T>{
	private T[] arr = (T[]) new Object[1];
	private int N;
	
	private void resize(int capability){
		T[] temp = (T[]) new Object[capability];
		for(int i=0;i<N;i++){
			temp[i] = arr[i];
		}
		arr = temp;
	}

	@Override
	public void push(T t) {
		if(N == arr.length)
			resize(arr.length * 2);
		arr[N++] = t;
	}

	@Override
	public T pop() {
		T t = arr[--N];
		arr[N] = null;
		if(N > 0 && N == arr.length/4)
			resize(arr.length/2);
		return t;
	}

	@Override
	public boolean isEmpty() {
		return N == 0;
	}

	@Override
	public int size() {
		return N;
	}

}
